package com.woniuxy.sales.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.sales.model.entity.Products;
import com.woniuxy.sales.service.ProductsService;
import com.woniuxy.sales.mapper.ProductsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * 【车辆表】
*/
@Service
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, Products>
    implements ProductsService{
    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    private final String key="car:list";

    @Override
    @Cacheable(cacheNames = key, keyGenerator = "keyGenerator")
    public Page<Products> findAll(int pageNum, int pageSize) {
        Page<Products> bookPage = new Page<>(pageNum, pageSize);

        Page<Products> page = productsMapper.selectPage(bookPage, null);

        return page;
    }

    @Override
    public Page<Products> findByType(int pageNum, int pageSize, int typeId) {
        //1.创建分页对象
        Page<Products> page = new Page<>(pageNum, pageSize);
        //2.按更新时间降序排序
        LambdaQueryWrapper<Products> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Products::getCategoryId, typeId);
        //3.执行查询
        productsMapper.selectPage(page, wrapper);
        //4.返回分页对象
        return page;
    }

    @Override
    public Page<Products> findByPrice(int pageNum, int pageSize, Integer minPrice, Integer maxPrice) {
        // 创建分页对象
        Page<Products> page = new Page<>(pageNum, pageSize);

        // 创建查询条件
        LambdaQueryWrapper<Products> wrapper = new LambdaQueryWrapper<>();

        // 添加价格条件
        if (minPrice != null) {
            wrapper.ge(Products::getPrice, minPrice); // 大于等于最小价格
        }
        if (maxPrice != null) {
            wrapper.le(Products::getPrice, maxPrice); // 小于等于最大价格
        }

        // 执行查询并返回结果
        productsMapper.selectPage(page, wrapper);
        return page;
    }

    @Override
    public Products addCar(String userId, Long id) {
        // 获取产品信息
        Products products = productsMapper.selectById(id);
        String key = "compareCar"+":"+userId;
        // 获取当前已经存储的车辆数量
        Set<String> existingKeys = redisTemplate.keys(key + ":*");
        // 如果已经有 3 个产品，提示用户删除后再添加
        if (existingKeys != null && existingKeys.size() >= 3) {
            throw new RuntimeException("对比列表中已有3个车辆，请删除后再添加");
        }
        // 添加新产品到 Redis
        redisTemplate.opsForValue().set(key + ":" + id, products, 1, TimeUnit.DAYS);
        return products;
    }


    @Override
    public List<Products> getCompare(String userId) {
        String key = "compareCar";
        Set<String> existingKeys = redisTemplate.keys(key + ":"+userId+":*");
        List<Products> productList = new ArrayList<>();
        // 遍历所有存储的键，获取产品信息
        if (existingKeys != null && !existingKeys.isEmpty()) {
            for (String existingKey : existingKeys) {
                // 提取产品 ID
                Long productId = Long.valueOf(existingKey.split(":")[1]);
                // 从 Redis 中获取产品信息
                Products product = (Products) redisTemplate.opsForValue().get(existingKey);
                if (product != null) {
                    productList.add(product);
                }
            }
        }
        return productList;
    }

    @Override
    public List<Products> removeCompare(String userId,String productId) {
        String key = "compareCar";
        String redisKey = key + ":"+userId+":" + productId; // 构造 Redis 键
        // 删除 Redis 中的产品
        redisTemplate.delete(redisKey);

        // 返回更新后的对比列表
        return getCompare(userId);
    }

    @Override
    public Boolean checkCompare(String productId) {
        String key = "compareCar";
        String redisKey = key + ":" + productId; // 构造 Redis 键

        // 检查 Redis 中是否存在该键
        return redisTemplate.hasKey(redisKey); // 如果存在，返回 true；否则返回 false
    }

    @Override
    public Products findById(Integer id) {
        return productsMapper.selectById(id);
    }
}




